package service

import (
	"C"
	"app-webapi/comm/g"
	"app-webapi/entity"
	"app-webapi/entity/dto"
	"encoding/json"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"gorm.io/gorm"
)

func GetTestEntities(testEntityList entity.TestEntityList) (testEntities []*entity.TestEntity, total int64, err error) {

	tx := g.Db.Model(&entity.TestEntity{})

	if len(testEntityList.TestName) > 0 {
		tx.Where("test_name LIKE ?", "%"+testEntityList.TestName+"%")
	}

	if err := tx.Count(&total).Error; err != nil {
		g.Logger.Errorf("计数端设备分页出错：%v", err.Error())
		return testEntities, 0, err
	}

	if total == 0 {
		return testEntities, 0, nil
	}

	if qErr := tx.Offset((testEntityList.Page.PageNum - 1) * testEntityList.Page.PageSize).Limit(testEntityList.Page.PageSize).Order("created_at desc").Find(&testEntities).Error; qErr != nil {
		g.Logger.Errorf("查询端设备分页列表出错：%v", err.Error())
		return testEntities, 0, qErr
	}
	return
}

func CreateTestEntity(testEntity entity.TestEntity) error {

	g.Db.Create(&testEntity)
	return nil

}

func UpdateTestEntity(testEntityDto dto.TestEntityDto) error {

	err := g.Db.Transaction(func(tx *gorm.DB) error {

		marshal, _ := json.Marshal(&testEntityDto)
		testEntity := entity.TestEntity{}
		_ = json.Unmarshal(marshal, &testEntity)
		//
		if err := g.Db.Model(&entity.TestEntity{}).Select("test_name", "test_age").
			Where(&entity.TestEntity{Model: gorm.Model{ID: testEntity.ID}}).
			Updates(&testEntity).Error; err != nil {
			return err
		}

		return nil

	})
	if err != nil {
		panic(err.Error())
	}

	return nil

}

func DetailTestEntity(id int) (*entity.TestEntity, error) {

	testEntity := entity.TestEntity{}
	tx := g.Db.Model(entity.TestEntity{}).Where(&entity.TestEntity{Model: gorm.Model{ID: uint(id)}}).Find(&testEntity)
	if tx.Error != nil {
		return nil, tx.Error
	}
	return &testEntity, nil
}

func DeleteTestEntity(id int) error {

	tx := g.Db.Delete(&entity.TestEntity{}, id)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}

func TestMqttEvent() {
	if token := g.MqttClient.Subscribe("/test/event", 0, func(client mqtt.Client, message mqtt.Message) {
		events := make([]entity.TestEntity, 0)
		err := json.Unmarshal(message.Payload(), &events)
		if err != nil {
			g.Logger.Errorf(err.Error())
		}
		// 开始处理告警事件
	}); token.Wait() && token.Error() != nil {
		g.Logger.Errorf(token.Error().Error())
	}
}

func TestAdd(testEntity entity.TestEntity) {
	g.Db.Model(entity.TestEntity{}).Save(&testEntity)
	return
}
